<?php
namespace App\Support;

class User {

	protected $curl;
	private $url;

	public function __construct(Curl $curl) {
		$this->curl = $curl;
		$this->url = env('APP_DEBUG') ? 'http://pass.71baomu.com' : 'http://6d.com.cn';
	}

	public function register(String $phone) {
		if (!$this->checkPhone($phone)) {
			return false;
		}
		$result = $this->curlSix('/interface/Login/register', compact('phone'));
		return $result['code'] == 0 ? $result['data']['user_id'] : false;
	}

	public function sendSms(String $phone, String $unique) {
		$result = $this->curlSix('/interface/Sms/sendSms', compact('unique', 'phone'));
		return $result['code'] == 0;
	}

	public function sendNotice(int $user_id, int $log_id, string $title, string $content) {
		$system = 'business';
		$result = $this->curlSix('/interface/Message/addBussinessMsg', compact('user_id', 'log_id', 'title', 'content', 'system'));
		return $result['code'] == 0;
	}

	public function modifyNotice(int $user_id, int $log_id, string $title, string $content) {
		$system = 'business';
		$result = $this->curlSix('/interface/Message/modifyBussinessMsg', compact('user_id', 'log_id', 'title', 'content', 'system'));
		return $result['code'] == 0;
	}

	public function setMsgRead(int $user_id, int $log_id) {
		$system = 'business';
		$result = $this->curlSix('/interface/Message/setMessageRead', compact('user_id', 'log_id', 'system'));
		return $result['code'] == 0;
	}

	private function curlSix($url, $data) {
		$data = $this->formatData($data);
		return json_decode($this->curl->post($this->url . $url . '/key/' . $data['key'], $data['data']), true);
	}

	private function checkPhone(String $phone) {
		return preg_match("/^1[345678]{1}\d{9}$/", $phone);
	}

	private function formatData(array $data) {
		$app_key = 'L8q{b=fk=4aJ3jM#cBDE8SaZ_A;bWAG]';
		ksort($data);
		$key = md5($app_key . implode('', $data));
		return compact('key', 'data');
	}
}